package com.ruoyi.web.controller.cs;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.annotation.CheckSwitch;
import com.ruoyi.common.core.controller.BasicsController;
import com.ruoyi.common.core.domain.Response;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.ResponsePageInfo;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.cs.domain.TGoods;
import com.ruoyi.cs.domain.TRedbagOpen;
import com.ruoyi.cs.domain.vo.PageInfoParamVo;
import com.ruoyi.cs.domain.vo.TRollBackVo;
import com.ruoyi.cs.domain.vo.TRollHomePageVo;
import com.ruoyi.cs.domain.vo.TRollVo;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.cs.mapper.TGoodsMapper;
import com.ruoyi.cs.service.ITGoodsService;
import com.ruoyi.framework.web.service.TokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.cs.domain.TRoll;
import com.ruoyi.cs.service.ITRollService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * ROLL房间信息Controller
 * 
 * @author ruoyi
 * @date 2021-03-25
 */
@Api(tags = {"ROLL房间信息"})
@RestController
@RequestMapping("/cs/roll")
@SuppressWarnings("all")
public class TRollController extends BasicsController
{
    private static final Logger log = LoggerFactory.getLogger(TRollController.class);

    @Autowired
    private ITRollService tRollService;

    @Autowired
    private ITGoodsService tgoodsService;

    @Autowired
    private TokenService tokenService;

    /**
     * ROLL房统计
     */
    @ApiOperation("ROLL房统计")
    @RequestMapping(name="ROLL房统计",value="rollCount",method = RequestMethod.GET)
    @PreAuthorize("@ss.hasPermi('cs:roll:rollCount')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime",value = "开始时间" ,dataType = "String", paramType = "query", required = false),
            @ApiImplicitParam(name = "endTime",value = "结束时间" , dataType = "String", paramType = "query", required = false),
    })
    public Response<Map<String,Object>> rollCount(String startTime, String endTime)
    {
        return Response.success(tRollService.rollCount(startTime, endTime));
    }

    /**
     * 后台查询ROLL房间信息列表
     */
    @ApiOperation("后台查询ROLL房间信息列表")
    @RequestMapping(name="后台查询ROLL房间信息列表",value="listBack",method = RequestMethod.POST)
    @PreAuthorize("@ss.hasPermi('cs:roll:listBack')")
    public ResponsePageInfo<TRollBackVo> listBack(@RequestBody TRollBackVo tRollBackVo)
    {
        startPage(tRollBackVo.getPageNum(),tRollBackVo.getPageSize());
        tRollBackVo.setBackStage(Constants.BACKSTAGE);
        List<TRollBackVo> list = tRollService.selectTRollList(tRollBackVo);
        return toResponsePageInfo(list);
    }

    /**
     * ROLL房中的饰品信息
     */
    @ApiOperation("ROLL房中的饰品信息")
    @RequestMapping(name="ROLL房中的饰品信息",value="rollGoodsList",method = RequestMethod.POST)
    @PreAuthorize("@ss.hasPermi('cs:roll:rollGoodsList')")
    public ResponsePageInfo<TRoll> rollGoodsList(@RequestBody TGoods tGoods)
    {
        startPage(tGoods.getPageNum(),tGoods.getPageSize());
        tGoods.setBackStage(Constants.BACKSTAGE);
        List<TGoods> list = tgoodsService.selectTGoodsList(tGoods);
        TRoll tRoll = tRollService.selectTRollById(tGoods.getGoodsBelongingId());
        return getDataTableObj(tRoll,list);
    }

    /**
     * 新增ROLL房间信息
     */
    @ApiOperation("新增ROLL房间信息")
    @RequestMapping(name="新增ROLL房间信息",value="add",method = RequestMethod.POST)
    @PreAuthorize("@ss.hasPermi('cs:roll:add')")
    @Log(title = "ROLL房间信息", businessType = BusinessType.INSERT)
    public Response add(@Validated  @RequestBody TRoll tRoll)
    {
        return tRollService.insertTRoll(tRoll);
    }

    /**
     * 修改ROLL房间信息
     */
    @ApiOperation("修改ROLL房间信息")
    @RequestMapping(name="修改ROLL房间信息",value="edit",method = RequestMethod.POST)
    @PreAuthorize("@ss.hasPermi('cs:roll:edit')")
    @Log(title = "ROLL房间信息", businessType = BusinessType.UPDATE)
    public Response edit(@RequestBody TRoll tRoll)
    {
        return tRollService.updateTRoll(tRoll);
    }

    /**
     * 上线ROLL
     */
    @ApiOperation("上线ROLL")
    @RequestMapping(name="上线ROLL",value="goOnline",method = RequestMethod.GET)
    @PreAuthorize("@ss.hasPermi('cs:roll:goOnline')")
    @Log(title = "上线ROLL", businessType = BusinessType.GOONLING)
    @ApiImplicitParam(name = "rollId",value = "roll房间ID" ,dataType = "String", paramType = "query", required = true)
    public Response<Integer> goOnline(String rollIds)
    {
        try {
            if (StringUtils.isNotEmpty(rollIds)) {
                String[] ids = rollIds.split(",");
                //饰品为空时不能上线（暂时不会有批量上线需求，如果后期增加批量上线需求则需要修改接口）
                List<TGoods> tGoods = tgoodsService.boxGoodsList(Constants.GOOGSBLTYPE1, rollIds);
                if (tGoods.size() <= 0) {
                    return Response.fail(Constants.FAILCODE,"上线房间的饰品不能为空!");
                }
                int row = tRollService.goOnline(ids);
                return toResponse(row);
            }else{
                return Response.fail(Constants.FAILCODE,"参数不能为空!");
            }
        } catch (Exception e) {
            log.error("上线ROLL信息异常:{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }
    /**
     * 结束ROLL
     */
    @ApiOperation("结束ROLL")
    @RequestMapping(name="结束ROLL",value="closure",method = RequestMethod.GET)
    @PreAuthorize("@ss.hasPermi('cs:roll:closure')")
    @Log(title = "结束ROLL", businessType = BusinessType.CLOSURE)
    @ApiImplicitParam(name = "rollId",value = "roll房间ID" ,dataType = "String", paramType = "query", required = true)
    public Response<Integer> closure(String rollIds)
    {
        try {
            if (StringUtils.isNotEmpty(rollIds)) {
                String[] ids = rollIds.split(",");
                int row = tRollService.closure(ids);
                return toResponse(row);
            }else{
                return Response.fail(Constants.FAILCODE,"参数不能为空!");
            }
        } catch (Exception e) {
            log.error("结束ROLL信息异常:{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    /**
     * ROLL房间手动开奖
     */
    @ApiOperation("ROLL房间手动开奖")
    @RequestMapping(name="ROLL房间手动开奖",value="manualLottery",method = RequestMethod.GET)
    @Log(title = "ROLL房间信息", businessType = BusinessType.LOTTERY)
    @ApiImplicitParam(name = "rollId",value = "roll房间ID" ,dataType = "String", paramType = "query", required = true)
    public Response manualLottery(String rollIds){
        try {
            if (StringUtils.isNotEmpty(rollIds)) {
                String[] ids = rollIds.split(",");
                List<TRoll> list = tRollService.batchQueryTRollList(ids);
                if(list.size()>0){
                    for (TRoll tRoll : list) {
                        if (tRoll.getDelFlag().contains(Constants.SUCCESS) && tRoll.getRollStatus().contains(Constants.ROLLSTATUS1)) {
                            tRollService.automaticLotteryHash(tRoll);
                        }
                    }
                }else {
                    return Response.fail(Constants.FAILCODE,"参数错误，没有ROLL房信息!");
                }
                return Response.success();
            }else{
                return Response.fail(Constants.FAILCODE,"参数不能为空!");
            }
        } catch (Exception e) {
            log.error("ROLL房间手动开奖异常:{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    /**
     * Roll房列表（下拉框）
     */
    @ApiOperation("ROLL房间列表")
    @RequestMapping(name = "ROLL房间列表", value = "robotRollList", method = RequestMethod.GET)
    public Response robotRollList() {
        List<TRoll> list = tRollService.robotRollList();
        return Response.success(list);
    }


    /*---------------------------------------------前端接口-----------------------------------*/

    /**
     * 查询ROLL房间所有信息列表
     */
//    @ApiOperation("web端查询ROLL房间所有信息列表")
//    @RequestMapping(name="查询ROLL房间所有信息列表",value="common/list",method = RequestMethod.GET)
//    @ApiImplicitParam(name = "rollName",value = "roll房名称" , dataType = "String", paramType = "query", required = false)
//    public Response<Map<String, Object>> list(String rollName)
//    {
//        String userId = "";
//        LoginUser loginUser = tokenService.getLoginUserWeb(ServletUtils.getRequest());
//        if(loginUser != null){
//            SysUser sysUser = loginUser.getUser();
//            userId = sysUser.getLoginUserId();
//        }
//        try {
//            Map<String, Object> resultMap  = tRollService.selectTRollListAll(userId,rollName);
//            return Response.success(resultMap);
//        } catch (Exception e) {
//            log.error("查询ROLL房间所有信息列表异常:{}",e.getMessage());
//            return Response.fail(e.getMessage());
//        }
//    }

    /**
     * 获得ROLL房的饰品列表、用户参与信息
     */
    @ApiOperation("web端获得ROLL房的饰品列表、用户参与信息")
    @RequestMapping(name="获得ROLL房的饰品列表、用户参与信息",value="common/getRollInfo",method = RequestMethod.GET)
    @ApiImplicitParam(name = "rollId",value = "roll房间ID" ,dataType = "String", paramType = "query", required = true)
    @Cacheable(value="twoSecondsCache", key="'getRollInfo'+#p0")
    public Response<TRollVo> getRollInfo(String rollId){

        String userId = "";
        LoginUser loginUser = tokenService.getLoginUserWeb(ServletUtils.getRequest());
        if(loginUser != null){
            SysUser sysUser = loginUser.getUser();
            userId = sysUser.getLoginUserId();
        }
        try {
            if (StringUtils.isNotEmpty(rollId)) {
                return  tRollService.getRollInfo(userId,rollId);
            }else {
                return Response.fail(Constants.FAILCODE,"参数不能为空!");
            }
        } catch (Exception e) {
            logger.error("获得ROLL房的饰品列表、用户参与信息异常:{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    /**
     * 用户参与ROLL房间
     * @param rollId ROLL房ID
     * @param userId 用户ID
     * @return
     */
    @CheckSwitch
    @ApiOperation("web端用户参与ROLL房间")
    @RequestMapping(name="用户参与ROLL房间",value="joinRoll",method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rollId",value = "roll房间ID" ,dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "rollPwd",value = "roll房间密码" , dataType = "String", paramType = "query", required = false),
    })
    @Log(title = "web端用户参与ROLL房间", businessType = BusinessType.INSERT)
    public Response joinRoll(String rollId,String rollPwd){
        try {
            LoginUser loginUser = tokenService.getLoginUserWeb(ServletUtils.getRequest());
            SysUser sysUser = loginUser.getUser();
            String userId = sysUser.getLoginUserId();
            return tRollService.joinRoll(rollId,userId,rollPwd);
        } catch (Exception e) {
            logger.error("用户参与ROLL房间功能异常:{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    /**
     * web端首页展示roll房列表
     * @param rollId ROLL房ID
     * @param userId 用户ID
     * @return
     */
    @ApiOperation("web端首页展示roll房列表")
    @RequestMapping(name="web端首页展示roll房列表",value="common/rollHomePageDisplay",method = RequestMethod.GET)
    public Response<List<TRollHomePageVo>> rollHomePageDisplay(){
        try {
            return Response.success(tRollService.selectHomePageDisplay());
        } catch (Exception e) {
            logger.error("首页展示roll房列表:{}",e.getMessage());
            return Response.fail(e.getMessage());
        }
    }

    /**
     * 查询ROLL房间所有信息列表
     */
    @ApiOperation("web端分页查询ROLL房间所有信息列表")
    @RequestMapping(name="分页查询ROLL房间所有信息列表",value="common/pageList",method = RequestMethod.POST)
    @Cacheable(value="twoSecondsCache", key="'rollPageList'+#p0")
    public ResponsePageInfo<TRollVo> pageList(@RequestBody PageInfoParamVo pageInfoParamVo)
    {
        String userId = "";
        LoginUser loginUser = tokenService.getLoginUserWeb(ServletUtils.getRequest());
        if(loginUser != null){
            SysUser sysUser = loginUser.getUser();
            userId = sysUser.getLoginUserId();
            pageInfoParamVo.setUserId(userId);
        }
        try {
            startPage(pageInfoParamVo.getPageNum(),pageInfoParamVo.getPageSize());
            List<TRollVo> tRollVoList = tRollService.selectTRollPageListAll(pageInfoParamVo);
            return toResponsePageInfo(tRollVoList);
        } catch (Exception e) {
            log.error("查询ROLL房间所有信息列表异常:{}",e.getMessage());
            ResponsePageInfo rep = new ResponsePageInfo();
            rep.setCode(Constants.FAILCODE);
            rep.setMsg(e.getMessage());
            return rep;
        }
    }

    /**
     * 查询ROLL房间所有信息列表
     */
    @ApiOperation("web端分页查询我参与的ROLL房间所有信息列表")
    @RequestMapping(name="分页查询我参与的ROLL房间所有信息列表",value="partakePageList",method = RequestMethod.POST)
    public ResponsePageInfo<TRollVo> partakePageList(@RequestBody PageInfoParamVo pageInfoParamVo)
    {
        String userId = "";
        LoginUser loginUser = tokenService.getLoginUserWeb(ServletUtils.getRequest());
        if(loginUser != null){
            SysUser sysUser = loginUser.getUser();
            userId = sysUser.getLoginUserId();
            pageInfoParamVo.setUserId(userId);
        }
        try {
            startPage(pageInfoParamVo.getPageNum(),pageInfoParamVo.getPageSize());
            List<TRollVo> tRollVoList = tRollService.selectMyRollPageList(pageInfoParamVo);
            return toResponsePageInfo(tRollVoList);
        } catch (Exception e) {
            log.error("查询ROLL房间所有信息列表异常:{}",e.getMessage());
            ResponsePageInfo rep = new ResponsePageInfo();
            rep.setCode(Constants.FAILCODE);
            rep.setMsg(e.getMessage());
            return rep;
        }
    }


}
